/*
 * LocalSocket.h
 *
 *  Created on: Jul 12, 2024
 *      Author: root
 */

#ifndef BSP_SERVER_LOCALSOCKET_H_
#define BSP_SERVER_LOCALSOCKET_H_
#include "basic_header.h"

namespace bsp {

class LocalSocket {
public:
	LocalSocket(std::string server_name, std::string client_name);
	virtual ~LocalSocket();

	int getSd() {
		return sd;
	}

	int open();
	void close();

	int read(char *buf, int size, int flag = MSG_DONTWAIT) {
		return recvfrom(sd, buf, size, flag, nullptr, nullptr);
	}

	int write(const char *buf, int size, int flag = MSG_DONTWAIT) { // send to server
		struct sockaddr_un addr;
		MEM_ZERO(addr);
		addr.sun_family = AF_LOCAL;
		strcpy(addr.sun_path, name.c_str());
		return sendto(sd, buf, size, 0, (struct sockaddr*) &addr, sizeof(addr));
	}

	int getBufferSize() {
		int n;
		socklen_t m = sizeof(n);
		ASSERT(getsockopt(sd, SOL_SOCKET, SO_RCVBUF, (void*) &n, &m) == 0, "");
		return n;
	}

	void setBufferSize(int n) {
		socklen_t m = sizeof(n);
		ASSERT(setsockopt(sd, SOL_SOCKET, SO_RCVBUF, (void*) &n, m) == 0, "");
	}

	static void test1();

private:
	int sd;
	int client_sd;
	std::string name;
	std::string client_name;

	int createSock(std::string &name);
};

} /* namespace bsp */

#endif /* BSP_SERVER_LOCALSOCKET_H_ */
